package com.example.selfcontrol.filter;

import com.example.selfcontrol.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/articles/auth/*")
public class ArticleAuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("/article/auth拦截到请求");

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        if(httpRequest.getMethod().equals("OPTIONS")) {
            // 吃掉OPTIONS请求，因为他上面没有authorization头，会卡出跨域报错
            filterChain.doFilter(servletRequest,servletResponse);
        }

        String jwtToken = JwtUtils.getJWTTokenFromHeader(httpRequest) ;
        if(jwtToken == null)    return ;
        boolean validate = JwtUtils.validateToken(jwtToken) ;
        System.out.println("是否放行:  " + validate);

        if(validate && jwtToken != null) {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
